<template>
  <div
    class="vxe-table--context-menu-wrapper virtual-table-menu modern-virtual-menu"
    ref="contextMenuRef"
    style="display: inline-block"
    :style="menuPosition"
  >
    <ul class="vxe-context-menu--option-wrapper modern-menu-wrapper">
      <li
        :class="{
          'link--disabled': item.disabled,
          'has-children': item.children && item.children.length > 0,
          'modern-menu-item': true
        }"
        v-for="item in menuOptions"
        :key="item.code"
        @mouseenter="handleMouseenter($event, item)"
        @mouseleave="handleMouseleave($event, item)"
      >
        <a class="vxe-context-menu--link modern-menu-link" @click="doMenu(item, $event)">
          <component :is="getLucideIcon(item)" :size="16" class="menu-icon" />
          <span class="vxe-context-menu--link-content menu-label">{{ item.name }}</span>
          <ChevronRight
            v-if="item.children && item.children.length > 0"
            :size="14"
            class="submenu-arrow"
          />
        </a>
        <!-- 子菜单 -->
        <ul
          v-if="item.children && item.children.length > 0 && activeSubmenu === item.code"
          class="vxe-context-menu--submenu modern-submenu"
        >
          <li
            v-for="subItem in item.children"
            :key="subItem.code"
            :class="{
              'link--disabled': subItem.disabled,
              'modern-submenu-item': true
            }"
            @mouseenter="handleSubmenuMouseenter"
            @mouseleave="handleSubmenuMouseleave"
          >
            <a
              class="vxe-context-menu--link modern-submenu-link"
              @click="doMenu(subItem, $event, item)"
            >
              <component :is="getLucideIcon(subItem)" :size="14" class="submenu-icon" />
              <span class="vxe-context-menu--link-content submenu-label">{{ subItem.name }}</span>
            </a>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import {
  Settings,
  Eye,
  Download,
  Copy,
  Trash2,
  Edit,
  Plus,
  PlusCircle,
  Minus,
  Move,
  MoreHorizontal,
  FileText,
  Folder,
  ArrowRight,
  ArrowDown,
  ChevronRight,
  Check,
  X,
  Info,
  Upload,
  Star,
  Bookmark,
  RotateCcw,
  Share,
  Lock,
  Globe,
  User,
  Mail,
  Phone,
  Calendar,
  Image,
  Video,
  FileAudio,
  Archive,
  HelpCircle,
  Filter,
  SortAsc,
  SortDesc,
  Search,
  Columns,
  Grid,
  List,
  BarChart,
  PieChart,
  TrendingUp,
  MousePointer,
  Target,
  Layers,
  FileDown,
  Clipboard,
  Type,
  Save,
  History,
  ShieldCheck,
  Navigation
} from 'lucide-vue-next'

const emit = defineEmits(['close', 'menuClick'])

const props = defineProps({
  // 事件
  e: {
    type: Object,
    default: () => ({})
  },
  // 右键点击行数据
  row: {
    type: Object,
    default: () => ({})
  },
  // 右键菜单配置
  menuConfig: {
    type: Object,
    default: () => ({
      body: {}
    })
  }
})

const menuPosition = computed(() => {
  return {
    left: `${props.e?.pageX}px`,
    top: `${props.e?.pageY}px`
  }
})
const menuOptions = ref([])
const activeSubmenu = ref(null)
let submenuTimer = null

const contextMenuRef = ref()
const doMenu = (menu, e, parentMenu) => {
  // 如果有子菜单，不执行点击操作
  if (menu.children && menu.children.length > 0) {
    e && e.preventDefault() && e.stopPropagation()
    return
  }

  if (!menu.disabled) {
    // 如果是子菜单项，传递父菜单信息
    if (parentMenu) {
      emit('menuClick', { ...menu, parent: parentMenu.code }, props.row)
    } else {
      emit('menuClick', menu, props.row)
    }
  }
  e && e.preventDefault() && e.stopPropagation()
}

const handleContextMenuClick = (e) => {
  let targetDom = e.target
  while (targetDom && targetDom != contextMenuRef.value) {
    targetDom = targetDom.parentNode
  }
  if (targetDom != contextMenuRef.value) {
    emit('close')
  }
}

const handleMouseenter = (e, item) => {
  e.currentTarget.classList.add('link--active')

  // 清除之前的定时器
  if (submenuTimer) {
    clearTimeout(submenuTimer)
    submenuTimer = null
  }

  // 如果有子菜单，显示子菜单
  if (item.children && item.children.length > 0) {
    activeSubmenu.value = item.code
  } else {
    // 延迟隐藏其他子菜单
    submenuTimer = setTimeout(() => {
      activeSubmenu.value = null
    }, 100)
  }
}

const handleMouseleave = (e, item) => {
  e.currentTarget.classList.remove('link--active')

  // 延迟隐藏子菜单，给用户时间移动到子菜单
  if (item.children && item.children.length > 0) {
    submenuTimer = setTimeout(() => {
      if (activeSubmenu.value === item.code) {
        activeSubmenu.value = null
      }
    }, 300)
  }
}

const handleSubmenuMouseenter = (e) => {
  // 清除隐藏定时器
  if (submenuTimer) {
    clearTimeout(submenuTimer)
    submenuTimer = null
  }
  e.currentTarget.classList.add('link--active')
}

const handleSubmenuMouseleave = (e) => {
  e.currentTarget.classList.remove('link--active')
}

// 基于menuConfig代码的精确图标映射
const getLucideIcon = (item) => {
  const code = item.code || ''
  const name = (item.name || '').toLowerCase()

  // 精确匹配menuConfig中的code值
  const iconMap = {
    // 添加操作 - 根据具体类型使用不同图标
    'add-current': Navigation, // 添加（当前位置）
    'add-next': ArrowDown, // 添加（下一行）
    'add-child': PlusCircle, // 添加（子节点）

    // 基本操作
    paste: Clipboard, // 粘贴
    delete: Trash2, // 删除
    copy: Copy, // 复制
    cut: Move, // 剪切
    edit: Edit, // 编辑

    // 导出操作 - 根据范围使用不同图标
    export_part_section: Layers, // 导出此节点所在节
    export_part_chapter: FileDown, // 导出此节点所在章
    export_full: Download, // 完整导出

    // 文件格式
    pdf: FileText, // PDF格式
    word: Type, // WORD格式
    excel: Grid, // Excel格式
    txt: FileText, // 文本格式

    // 视图操作
    view: Eye, // 查看
    preview: Eye, // 预览
    expand: Plus, // 展开
    collapse: Minus, // 折叠

    // 排序和过滤
    'sort-asc': SortAsc, // 升序
    'sort-desc': SortDesc, // 降序
    filter: Filter, // 过滤
    search: Search, // 搜索

    // 权限操作
    permission: ShieldCheck, // 权限设置
    share: Share, // 分享
    lock: Lock, // 锁定
    unlock: Globe, // 解锁

    // 其他操作
    info: Info, // 信息
    settings: Settings, // 设置
    history: History, // 历史
    refresh: RotateCcw, // 刷新
    save: Save, // 保存
    upload: Upload, // 上传
    download: Download, // 下载
    more: MoreHorizontal // 更多
  }

  // 首先尝试精确匹配code
  if (iconMap[code]) {
    return iconMap[code]
  }

  // 然后尝试根据name的关键词匹配
  if (name.includes('添加') || name.includes('add')) {
    if (name.includes('当前') || name.includes('current')) return Navigation
    if (name.includes('下') || name.includes('next')) return ArrowDown
    if (name.includes('子') || name.includes('child')) return PlusCircle
    return Plus
  }

  if (name.includes('导出') || name.includes('export')) {
    if (name.includes('节') || name.includes('section')) return Layers
    if (name.includes('章') || name.includes('chapter')) return FileDown
    return Download
  }

  if (name.includes('粘贴') || name.includes('paste')) return Clipboard
  if (name.includes('删除') || name.includes('delete')) return Trash2
  if (name.includes('pdf')) return FileText
  if (name.includes('word')) return Type

  // 默认图标
  return MoreHorizontal
}

onMounted(() => {
  if (props.menuConfig?.visibleMethod && typeof props.menuConfig?.visibleMethod === 'function') {
    props.menuConfig?.visibleMethod({
      options: props.menuConfig?.body?.options,
      row: props.row
    })
  }
  menuOptions.value = (props.menuConfig?.body?.options || []).flat()
  document.addEventListener('click', handleContextMenuClick, true)
})
onUnmounted(() => {
  document.removeEventListener('click', handleContextMenuClick, true)
})
</script>
<style lang="less">
// 覆盖 VXE Table 默认右键菜单样式
.vxe-table--context-menu-clild-wrapper,
.vxe-table--context-menu-wrapper {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08), 0 0 0 1px rgba(0, 0, 0, 0.04) !important;
  border: none !important;
  border-radius: var(--modern-menu-radius) !important;
}

// 删除 VXE Table 默认的 link--active 样式
.vxe-context-menu--option-wrapper li.link--active,
.vxe-table--context-menu-clild-wrapper li.link--active {
  background-color: transparent !important;
  border-color: transparent !important;
}

// 修复 hover 样式优先级问题
.vxe-table--context-menu-wrapper
  .vxe-context-menu--option-wrapper
  .modern-menu-item:first-child
  .modern-menu-link:hover {
  background: var(--modern-menu-item-hover-bg) !important;
  color: var(--modern-menu-item-hover-color) !important;
}

.virtual-table-menu.modern-virtual-menu {
  z-index: 9999;
  position: fixed;

  .modern-menu-wrapper {
    background: var(--modern-menu-bg);
    border: 1px solid var(--modern-menu-border);
    border-radius: var(--modern-menu-radius);
    box-shadow: var(--modern-menu-shadow);
    padding: 4px;
    min-width: 160px;
    list-style: none;
    margin: 0;
    transition: all var(--modern-menu-animation-duration) var(--modern-menu-animation-easing);
    animation: menuFadeIn 0.15s ease-out;

    .modern-menu-item {
      position: relative;
      padding: 0;
      margin-bottom: 0;

      &:last-child {
        margin-bottom: 0;
      }

      .modern-menu-link {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 6px 10px;
        border-radius: var(--modern-menu-item-radius);
        color: var(--modern-menu-item-color);
        text-decoration: none;
        font-size: 13px;
        font-weight: 400;
        cursor: pointer;
        line-height: 1.4;
        transition: all var(--modern-menu-animation-duration) var(--modern-menu-animation-easing);

        .menu-icon {
          flex-shrink: 0;
          color: var(--modern-menu-icon-color);
          transition: color var(--modern-menu-animation-duration)
            var(--modern-menu-animation-easing);
        }

        .menu-label {
          flex: 1;
          white-space: nowrap;
        }

        .submenu-arrow {
          flex-shrink: 0;
          color: var(--modern-menu-icon-color);
          transition: color var(--modern-menu-animation-duration)
            var(--modern-menu-animation-easing);
        }

        &:hover {
          background: var(--modern-menu-item-hover-bg);
          color: var(--modern-menu-item-hover-color);

          .menu-icon,
          .submenu-arrow {
            color: var(--modern-menu-icon-hover-color);
          }
        }
      }

      &.link--disabled {
        .modern-menu-link {
          color: var(--modern-menu-item-disabled-color);
          cursor: not-allowed;

          &:hover {
            background: transparent;
            color: var(--modern-menu-item-disabled-color);

            .menu-icon,
            .submenu-arrow {
              color: var(--modern-menu-icon-disabled-color);
            }
          }
        }
      }

      &.has-children {
        position: relative;
      }
    }
  }

  .modern-submenu {
    position: absolute;
    left: calc(100% + 4px);
    top: 0;
    min-width: 140px;
    background: var(--modern-submenu-bg);
    border: 1px solid var(--modern-menu-border);
    border-radius: var(--modern-submenu-radius);
    box-shadow: var(--modern-submenu-shadow);
    padding: 4px;
    list-style: none;
    z-index: 10000;
    margin: 0;
    animation: submenuFadeIn 0.12s ease-out;

    .modern-submenu-item {
      padding: 0;
      margin-bottom: 0;

      &:last-child {
        margin-bottom: 0;
      }

      .modern-submenu-link {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 5px 8px;
        border-radius: var(--modern-submenu-item-radius);
        color: var(--modern-menu-item-color);
        text-decoration: none;
        font-size: 12px;
        font-weight: 400;
        cursor: pointer;
        line-height: 1.4;
        transition: all var(--modern-menu-animation-duration) var(--modern-menu-animation-easing);

        .submenu-icon {
          flex-shrink: 0;
          color: var(--modern-menu-icon-color);
          transition: color var(--modern-menu-animation-duration)
            var(--modern-menu-animation-easing);
        }

        .submenu-label {
          flex: 1;
          white-space: nowrap;
        }

        &:hover {
          background: var(--modern-menu-item-hover-bg);
          color: var(--modern-menu-item-hover-color);

          .submenu-icon {
            color: var(--modern-menu-icon-hover-color);
          }
        }
      }

      &.link--disabled {
        .modern-submenu-link {
          color: var(--modern-menu-item-disabled-color);
          cursor: not-allowed;

          &:hover {
            background: transparent;
            color: var(--modern-menu-item-disabled-color);

            .submenu-icon {
              color: var(--modern-menu-icon-disabled-color);
            }
          }
        }
      }
    }
  }
}

// 简化的动画效果
@keyframes menuFadeIn {
  0% {
    opacity: 0;
    transform: scale(0.98) translateY(-4px);
  }
  100% {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

@keyframes submenuFadeIn {
  0% {
    opacity: 0;
    transform: scale(0.98) translateX(-4px);
  }
  100% {
    opacity: 1;
    transform: scale(1) translateX(0);
  }
}
</style>
